const koaRouter = require('koa-router')

const User = require('../model/user')
const Code = require('../model/code')
const getCode = require('../service/aliyun')
const { PhoneValidator, RegisterValidator,BindEmailValidator } = require('../validater')
const { Auth } = require('../middlewares/auth')

const router = new koaRouter({
    prefix:'/api/user'
})

// 注册用户
router.post('/register', async ctx => {
    const v = new RegisterValidator().validate(ctx)
    const { phone, password, code } = v.get('body')
    await User.Register( phone, password, code,ctx)
})

// 是否注册
router.post('/isregister', async ctx => {
    const v = new PhoneValidator().validate(ctx)
    const phone = v.get('body.phone')
    
    const isRegister = await User.isRegister(phone)
    ctx.body = {isRegister}
})

// 获取验证码
router.post('/getCode', async ctx => { 
    const v = new PhoneValidator().validate(ctx)
    const phone = v.get('body.phone')
    await User.getCode(phone)
})

// 绑定email
router.put('/bindEmail',new Auth().m,async ctx => {
    const v = new BindEmailValidator().validate(ctx)
    const email = v.get('body.email')
    const uid = ctx.auth.uid
    await User.update({email},{where:{uid}})
    throw new global.errs.Success('邮箱绑定成功')
})

// 获取个人信息
router.get('/userinfo',new Auth().m,async ctx => {
    const uid = ctx.auth.uid
    const user = await User.findOne({ where: { uid } ,attributes:['phone','email']})
    ctx.body = user
})

module.exports = router